<template>
	<view class="">

		<canvas class="canvas" :style="'width:'+width+'px;height:'+height+'px'" canvas-id="idcard" id="idcard"></canvas>

		<view class="form">
			<view class="form_item">
				<view class="form_item_label">
					姓名
				</view>
				<view class="form_item_input">
					<input class="uni-input" focus placeholder="请输入姓名" v-model="formData.name" />
				</view>
			</view>
			<view class="form_item">
				<view class="form_item_label">
					民族
				</view>
				<view class="form_item_input">
					<input class="uni-input" placeholder="请输入民族" v-model="formData.nation" />
				</view>
			</view>

			<view class="form_item">
				<view class="form_item_label">
					完整地址
				</view>
				<view class="form_item_input">
					<textarea class="form_item_textarea" placeholder="请补充详细地址,无需输入省份以及县市..." v-model="formData.address"
						auto-height />
				</view>
			</view>
			<view class="form_item">
				<view class="form_item_label">
					选择头像
				</view>
				<view class="form_item_input" @click="choose">
					<view class="rui-btn">{{avatar ? "头像展示中...":"请选择您的头像"}}</view>
				</view>
			</view>

			<rui-button @click="draw" title="立即生成"></rui-button>
		</view>

		<view style="margin: 60rpx;text-align: center;font-size: 24rpx;color: #999;" @click="down">
			此图片仅用于展示，不能做其他非法用途。
		</view>

	</view>
</template>

<script setup>
	import {
		ref
	} from "vue"

	import {
		onLoad
	} from "@dcloudio/uni-app"

	let formData = ref({
		address: "",
		name: "",
		nation: "汉"
	})
	let ctx;
	let opts = ref({
		idcard: "",
		regions: "",
		sex: ""
	});
	let avatar = ref("");
	onLoad(option => {
		opts.value = option
		ctx = uni.createCanvasContext('idcard')
		draw()
	})



	let width = ref(255 * 1.58),
		height = ref(255);

	let label_size = 13,
		label_color = "#2b80a7",
		spacing = 20;

	let value_size = 15,
		value_color = "#333"

	let url = "/static/idcard.jpg";
	const drawIMG = (url, callback) => {
		uni.downloadFile({
			url,
			success: (res) => {
				callback(res.tempFilePath)
			},
			fail(err) {
				console.log(err)
			}
		})
	}


	const down = () => {
		uni.canvasToTempFilePath({
			width: width.value,
			height: height.value,
			destWidth: width.value * 2,
			destHeight: height.value * 2,
			canvasId: 'idcard',
			success: function(res) {
				// 在H5平台下，tempFilePath 为 base64
				console.log(res.tempFilePath)
				// #ifdef H5
				base64ToImage(res.tempFilePath)
				// #endif
				uni.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success: () => {
						console.log('save success');
						uni.showToast({
							title: "图片已经保存到您的相册~"
						})
					}
				});
			}
		})
	}


	const base64ToImage = (base64Data, filename = 'image.png') => {
		// 将base64的数据部分提取出来
		const arr = base64Data.split(',');
		const mime = arr[0].match(/:(.*?);/)[1];
		const bstr = atob(arr[1]);
		let n = bstr.length;
		const u8arr = new Uint8Array(n);

		while (n--) {
			u8arr[n] = bstr.charCodeAt(n);
		}

		// 创建Blob对象
		const blob = new Blob([u8arr], {
			type: mime
		});

		// 创建链接元素用于下载
		const url = URL.createObjectURL(blob);
		const a = document.createElement('a');

		a.href = url;
		a.download = filename;
		document.body.appendChild(a);
		a.click();

		// 清理临时对象和URL
		document.body.removeChild(a);
		window.URL.revokeObjectURL(url);
	}


	const choose = () => {
		uni.chooseImage({
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				avatar.value = tempFilePaths[0]
				draw()
			}
		});
	}

	const draw = () => {
		drawIMG(url, path => {
			ctx.drawImage(path, 0, 0, width.value, height.value);
			createName(formData.value.name)
			createSex(opts.value.sex, formData.value.nation || '汉')
			createBirth(opts.value.idcard)
			createAddress(opts.value.regions + formData.value.address)
			createIdcard(opts.value.idcard)
			createAvatar();
			ctx.draw()
		})
	}

	const createAvatar = () => {
		ctx.globalCompositeOperation = 'multiply';
		if (avatar.value) {
			ctx.drawImage(avatar.value, 240, 30, 125, 155);
		}
	}

	const createName = (name) => {
		let x = 35,
			y = 52;
		ctx.setFontSize(label_size);
		ctx.setFillStyle(label_color);
		ctx.fillText('姓', x, y);
		ctx.fillText('名', x + spacing, y);

		ctx.setFontSize(18)
		ctx.setFillStyle(value_color);

		let value_spacing = 20;
		let vlaue_x = 25
		if (name.length < 3) {
			value_spacing = 30;
			vlaue_x = 15
		}
		let user_name = name.split('');
		for (let i = 0; i < name.length; i++) {
			x = x + value_spacing;
			ctx.fillText(user_name[i], x + vlaue_x, y + 2);
		}


	}
	const createSex = (sex, nation) => {
		let x = 35,
			y = 87;
		ctx.setFontSize(label_size);
		ctx.setFillStyle(label_color);
		ctx.fillText('性', x, y);
		ctx.fillText('别', x + spacing, y);
		//民族
		ctx.fillText('民', x + 88, y);
		ctx.fillText('族', x + 88 + spacing, y);

		ctx.setFontSize(value_size)
		ctx.setFillStyle(value_color);
		ctx.fillText(sex, x + 45, y);
		ctx.fillText(nation, x + 125, y);
	}

	const createBirth = (idcard) => {

		let year = idcard.substr(6, 4)
		let m_start = 10;
		let m_number = 2
		if (idcard[m_start] == 0) {
			m_start += 1;
			m_number -= 1;
		}
		let month = idcard.substr(m_start, m_number)

		let d_start = 12;
		let d_number = 2
		if (idcard[d_start] == 0) {
			d_start += 1;
			d_number -= 1;
		}
		let day = idcard.substr(d_start, d_number)


		let x = 35,
			y = 115;
		ctx.setFontSize(label_size);
		ctx.setFillStyle(label_color);
		ctx.fillText('出', x, y);
		ctx.fillText('生', x + spacing, y);

		//年月日
		ctx.fillText('年', x + 88, y);
		ctx.fillText('月', x + 126, y);
		ctx.fillText('日', x + 164, y);

		ctx.setFontSize(value_size)
		ctx.setFillStyle(value_color);
		ctx.fillText(year, x + 45, y);
		let m_x = month < 10 ? 110 : 105;
		ctx.fillText(month, x + m_x, y);
		let d_x = day < 10 ? 148 : 144;
		ctx.fillText(day, x + d_x, y);

	}


	const createAddress = (address) => {
		let x = 35,
			y = 147;
		ctx.setFontSize(label_size);
		ctx.setFillStyle(label_color);
		ctx.fillText('地', x, y);
		ctx.fillText('址', x + spacing, y);

		ctx.setGlobalAlpha(0.9);
		ctx.setFontSize(value_size)
		ctx.setFillStyle(value_color);

		let arr = splitStringByLength(address, 10);
		for (let i = 0; i < arr.length; i++) {
			ctx.fillText(arr[i], x + 45, y + (i * 20) + 2);
		}
	}
	const createIdcard = (idcard) => {
		let x = 35,
			y = 228;
		ctx.setFontSize(label_size);
		ctx.setFillStyle(label_color);
		let s = 15
		let label = "公民身份号码"
		let arr = label.split("")
		let start = 15;
		for (let i = 0; i < arr.length; i++) {
			ctx.fillText(arr[i], x + (start * i), y);
		}
		ctx.font = '20px "黑体",Arial';
		ctx.setGlobalAlpha(0.9);
		// ctx.setFontSize(20)
		ctx.setFillStyle(value_color);
		ctx.fillText(idcard, x + 100, y + 2);
	}

	const splitStringByLength = (str, num) => {
		var array = [];
		var len = str.length;
		for (var i = 0; i < (len / num); i++) {
			let start = i * num;
			let end = start + num;
			array.push(str.substring(start, end));
		}
		return array;
	}
</script>

<style lang="scss" scoped>
	.canvas {
		margin: 30rpx auto;
	}

	.form {
		margin: 30rpx;

		&_item {
			display: flex;
			align-items: center;
			padding: 10rpx 0;
			margin-bottom: 20rpx;

			&_label {
				width: 130rpx;
				text-align: right;
				color: #999;
				font-size: 24rpx;
			}

			&_textarea {
				font-size: 28rpx;
			}

			&_input {
				border-bottom: 1rpx solid #eee;
				padding: 10rpx;
				margin-left: 20rpx;
				width: calc(100% - 150rpx);
			}
		}
	}
</style>